package com.example.concurrentprogramming8016.future.completablefuture;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * @author liyanhao
 * @Date 2023-01-08 17:33
 * 异常处理
 */
public class CompletableFutureDemo2 {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            int num = new Random().nextInt(10);
            System.out.println("随机数:" + num);
            if (num % 2 == 0) {
                int i = 12 % 0;
            }
            System.out.println("执行结束");
            return "test";
        });
        future.whenComplete(new BiConsumer<String, Throwable>() {
            @Override
            public void accept(String s, Throwable throwable) {
                System.out.println(s + "执行完成");
            }
        });
        future.exceptionally(new Function<Throwable, String>() {
            @Override
            public String apply(Throwable throwable) {
                System.out.println("执行失败:" + throwable.getMessage());
                return "异常了";
            }
        }).join();

    }
}
